package com.ffyc.resale.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ffyc.resale.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping(path = "/api/uploadCtl")
public class UploadController {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /*
    后端接收文件包装类
    @RequestParam("file") CommonsMultipartFile file//spring中提供发文件
    */
    @RequestMapping(path = "/uploadimg",method = RequestMethod.POST)
    public Result uploadImg(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        System.out.println(file.getInputStream());// 文件名
        System.out.println(file.getOriginalFilename());// 文件对象

        //将文件上传到阿里云oss对象空间中
        //为了避免上传的文件重名,重新生成一个文件名
        String newFileName = new Date().getTime()+file.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);
        //长传文件
        ossClient.putObject(bucketName, newFileName,file.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newFileName;

        return new Result(200,"上传成功",url);
    }
}
